package com.atguigu.crowd.filter;

import com.atguigu.crowd.constant.AccessPassResources;
import com.atguigu.crowd.constant.CrowdConstan;
import com.atguigu.crowd.entity.vo.MemberLoginVo;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author zzqstart
 * @Description
 * @date 2022-09-19 13:27
 */
@Component
public class CrowdAccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 通过请求上下文获取当前上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 通过当前上下文获取当前请求
        HttpServletRequest request = currentContext.getRequest();
        // 获取当前请求的servletPath
        String servletPath = request.getServletPath();
        // 判断当前资源是否放行
        if (AccessPassResources.PASS_RES_SET.contains(servletPath)){
            return false;
        }
        // 判断是否是静态资源
        boolean whetherStaticResources = AccessPassResources.judgeCurrentServletWhetherStaticResources(servletPath);
        if (whetherStaticResources){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取request
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        // 获取session对象
        HttpSession session = request.getSession();
        // 获取session中的登录对象，没有则创建session
        MemberLoginVo loginMember = (MemberLoginVo) session.getAttribute(CrowdConstan.ATTR_NAME_LOGIN_MEMBER);
        // 判断是否登录
        if (loginMember == null){
            // 将错误信息带回登录界面
            session.setAttribute(CrowdConstan.ATTR_NAME_MEMBER_LOGIN_FAILED,CrowdConstan.MESSAGE_ACCESS_FORBIDEN);
            // 重定向到登录页面
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.sendRedirect("/auth/member/to/login/page");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
